from __future__ import absolute_import

import os
import importlib
from sqlalchemy import MetaData
from scopt.util import message as msg_util
from scopt.util.misc import dir_name, accept
from scopt.mpu.business.db import DB
from scopt.mpu.business.core import handlers as core
from scopt.mpu.business.devel import handlers as devel


@accept(status=['AFP'])
def handle(data_packet):
    handler_id = msg_util.get_handler_id(data_packet)
    if handler_id in _BUSINESS_HANDLERS:
        data_packet = _DB.init(data_packet)
        business_handler = _BUSINESS_HANDLERS[handler_id]
        data_packet = business_handler(data_packet)
        if 'response' not in data_packet['message']:
            data_packet = msg_util.exception(data_packet,
                                             'business.missing.response')
    return data_packet


def parse_handlers(modules):
    business_handlers = {}
    for module_name in modules:
        handler_name = __name__ + '.' + module_name + '.handlers'
        handler_module = importlib.import_module(handler_name)
        business_handlers.update(handler_module.message.registry())
    return business_handlers


def parse_model(modules):
    metadata = MetaData()
    for module_name in modules:
        model_name = __name__ + '.' + module_name + '.model'
        try:
            model = importlib.import_module(model_name)
            model.update(metadata)
        except ImportError:
            pass
    return metadata


def parse_i18n(modules):
    i18n = {'business': os.path.join(dir_name(__file__), 'i18n')}
    for module_name in modules:
        module_path = os.path.join(dir_name(__file__), module_name, 'i18n')
        i18n.update({module_name: module_path})
    return i18n


def parse_modules(modules):
    business_modules = []
    for module_name in modules:
        handler_name = __name__ + '.' + module_name + '.handlers'
        handler_module = importlib.import_module(handler_name)
        business_modules.append(handler_module)
    return business_modules

_MODULES = ('core',
            'devel',
            'settings',
            'inventory')

I18N = parse_i18n(_MODULES)
_BUSINESS_HANDLERS = parse_handlers(_MODULES)
MODEL = parse_model(_MODULES)
_DB = DB({'lds/BDS': MODEL})

core.init(_BUSINESS_HANDLERS)
devel.init(_BUSINESS_HANDLERS, parse_modules(_MODULES))
